﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace TotalSystems.Core.Controls
{
    public partial class TsClock : UserControl
    {
        public Storyboard timer = new Storyboard(); //timer 
        private const double radian = Math.PI / 180; //radian 
        private bool started = false;
        private double MaxHandLength { get; set; } //shorter length of width:height 
        private Point CenterPoint { get; set; }

        public TsClock()
        {
            InitializeComponent();
            timer.Duration = TimeSpan.FromMilliseconds(50);
            timer.Completed += new EventHandler(Timer_Completed);
            timer.Begin();
        }


        protected void Timer_Completed(object sender, EventArgs e)
        {
            double aw2 = LayoutRoot.ActualWidth / 2, ah2 = LayoutRoot.ActualHeight / 2;

            if (!started || CenterPoint.X != aw2 || CenterPoint.Y != ah2)
            {
                //Reset the centerpoint & ratios on startup or if the window resizes. 
                CenterPoint = new Point(aw2, ah2);
                MaxHandLength = Math.Min(CenterPoint.X, CenterPoint.Y);
                el.Height = el.Width = ((MaxHandLength) * 2);
                lh.X1 = lm.X1 = ls.X1 = CenterPoint.X;
                lh.Y1 = lm.Y1 = ls.Y1 = CenterPoint.Y;
                started = true;
            }

            var now = System.DateTime.Now;
            //line hour - apply partial split for smoother transition and update more than onces per second. 
            ChangeHand(lh, MaxHandLength - 23, 30 * (now.Hour + ((double)now.Minute) / 60));
            //line minute 
            ChangeHand(lm, MaxHandLength - 14, 6 * (now.Minute + ((double)now.Second) / 60));
            //line second 
            ChangeHand(ls, MaxHandLength - 10, 6 * (now.Second + ((double)now.Millisecond) / 1000));
            timer.Begin();
        }


        protected void ChangeHand(Line l, double r, double a)
        {
            //Calculate the point on the circumference based on Center, Radius & Angle. 
            var i = a * radian;
            l.X2 = CenterPoint.X + r * Math.Sin(i);
            l.Y2 = CenterPoint.Y + r * -Math.Cos(i);

        }
    }
}

    

